import { defineConfig, loadEnv } from 'vite'
import path, { resolve } from 'path'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite' //按需引入
import Components from 'unplugin-vue-components/vite' //按需引入
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers' //按需引入
import { viteMockServe } from 'vite-plugin-mock' //使用mock数据模拟请求
import viteCompression from 'vite-plugin-compression' //引入代码压缩
import { visualizer } from 'rollup-plugin-visualizer' //打包分析
import viteImagemin from 'vite-plugin-imagemin' //图片压缩
import importToCDN from 'vite-plugin-cdn-import' //通过cdn方式引入ui框架


// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  //环境变量
  const env = loadEnv(mode, process.cwd());
  return {
    base: "./", //配置开发或生产环境的公共基础路径（绝对路径/foo/ ，完整url:https://bar.com/foo/，相对路径 ./）
    plugins: [
      vue(),
      visualizer({ //打包分析
        open: true,
        gzipSize: true
      }),
      viteCompression({ //代码压缩
        deleteOriginFile: true, //压缩后是否删除源文件
        disable: false //是否禁用压缩
      }),
      AutoImport({ //element 按需引入
        resolvers: [ElementPlusResolver()]
      }),
      Components({ //element 按需引入
        resolvers: [ElementPlusResolver()]
      }),
      // importToCDN({ //通过cdn方式引入element（在开发环境下不生效）
      //   modules: [
      //     {
      //       name: 'vue',
      //       var: 'Vue',
      //       path: 'https://unpkg.com/vue@3'
      //     },
      //     {
      //       name: 'element-plus',
      //       var: 'ElementPlus',
      //       path: "https://unpkg.com/element-plus",
      //       css: "https://cdn.jsdelivr.net/npm/element-plus/dist/index.css"
      //     }
      //   ]
      // }),
      viteMockServe({ //使用mock数据模拟请求
        mockPath: 'mock'
      }),
      viteImagemin({ //图片压缩
        gifsicle: {
          optimizationLevel: 7,
          interlaced: false
        },
        optipng: {
          optimizationLevel: 7
        },
        mozjpeg: {
          quality: 20
        },
        pngquant: {
          quality: [0.8, 0.9],
          speed: 4
        },
        svgo: {
          plugins: [
            {
              name: 'removeViewBox'
            },
            {
              name: 'removeEmptyAttrs',
              active: false
            }
          ]
        }
      })
    ],
    resolve: {
      alias: { //配置路径别名
        "@": resolve(__dirname, './src')
      }
    },
    server: {
      proxy: { //配置代理
        '/api': {
          target: env.VITE_APP_API_URL, //代理地址
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, "") //路径重写（在生产环境将api替换为“空”）
        }
      }
    },
    build: {
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true, //生产环境移除console
          drop_debugger: true //生产环境移入debugger
        }
      }
    }
  }
})
